<?php
// +----------------------------------------------------------------------
// | 奇乐中介担保交易系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com   
// +----------------------------------------------------------------------
// | 产品文档：http://www.qilecms.com/doc
// +----------------------------------------------------------------------
// | 开发作者: 奇乐CMS
// +----------------------------------------------------------------------
// | 版权说明：这不是一个自由软件！本产品仅限个人使用，但请务必保留底部版权，以免产生不必要的纠纷,
// | 您只能在不用于商业目的的前提下对程序代码进行修改和使用，
// | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\controller;
use think\DB;
use think\facade\Request;
class Admin extends Base
{

   	//管理员列表
   public function index(){
      $alias = 'b';        //需要别名时写别名，不需要的时候留空 
      $defaultWhere = '';
      $defaultOrder = 'b.create_time desc';
    //接收搜索表单数据
      $SearchFormData = $this->getSearchFormData($defaultWhere,$defaultOrder);
      $where = $SearchFormData['where'];
      $order = $SearchFormData['order'];
      $pageNum = $SearchFormData['pageNum'];

//组建关键词数据
     $keywordsData  =[
                  [
                  'field'   =>'uid', //字段名
                  'name'    =>'管理员UID', //文本显示名称
                  'alias'   => $alias,  //字段对应的别名
                  ],
                  [
                  'field'   =>'username',
                  'name'    =>'管理员用户名',
                  'alias'   => $alias,
                  ],
                  [
                  'field'   =>'role_name',
                  'name'    =>'角色组',
                  'alias'   => 'c',
                  ],
     ];
//组建日期筛选   
       $dateData = [
                  [
                  'title'        =>'创建时间',  //标签显示名称
                  'field'        =>'create_time', //筛选字段
                  'start_name'   =>'开始时间', //开始时间
                  'end_name'     =>'结束时间', //结束时间
                  'alias'        => $alias,  //字段别名
                  ],
            
              ];
//单个字段筛选
    $customSingleField =[
                            [
                             'name'  =>'状态',
                             'field' => 'status', 
                             'data'  => [ 0 =>'禁用',1=>'启用'],
                             'alias' =>$alias,
                            ]
                       ]; 
// 组件字段组筛选
    $groupData   = [];
    $orderData   = [];  

     $this->assign('keywordsData',$keywordsData);
     $this->assign('customSingleField',$customSingleField);
     $this->assign('groupData',$groupData);
     $this->assign('dateData',$dateData);
     $this->assign('orderData',$orderData);

     $list = DB::name('admin_role_access')->alias('a')
     ->join("admin b","b.uid = a.uid","LEFT")
     ->join("admin_role c","c.role_id = a.role_id","LEFT")
     ->where($where)
     ->order($order)
     ->paginate($pageNum);
     $page = $list->render();
     $this->assign('page', $page);
     $this->assign('list', $list->toArray()['data']);
     return $this->fetch();

    
   }

//增加
  public function add(){
    $param = $this->request->param(); 
    if($this->request->isPost()){   

        //验证
        $rule =[
          'username'=>'require|regex:[a-zA-Z][a-zA-Z0-9_]{4,20}',
          'password'=>'require|min:6',
          'repassword'=>'require|min:6',
        ];
        $msg= [
         'username.require' =>'管理员名称不能为空',
         'username.regex' =>'管理员名只能是5-20个字符串，必须字母开头、数字、字母、下划线',
         'password.require' =>'登陆密码不能为空',
         'password.min' =>'登陆密码至少6位', 
         'repassword.require' =>'重复密码不能为空',
         'repassword.min' =>'重复密码至少6位',    
        ];

         $error = $this->checkSubmit($param,$rule,$msg);  
       if($error){
              return error_json($error);
         }
         // 验证两次密码输入是否一致
         if($param['repassword'] != $param['password']){
              return error_json('重复密码与登录密码不一致'); 
         } 
        
        //表单数据
          $username = $param['username']; //接受表单管理员用户名
 
         //验证用户名是否重复
          $where['username'] = $username;
          $admininfo = model('admin')->getAdminInfo($where);

          if($admininfo){
            return error_json('抱歉，该管理员已经存在，请更换用户名'); 
          }
       
          $data['username'] = $username;

          $random_text       = random_text(8);
          $data['password']  = password_key($username,$param['password'],$random_text);
          $data['passsalt']  = $random_text;

          $data['status'] = !empty($param['status'])?1:0;
          $admin =  model('admin')->addData($data);
          if($admin->id){
//添加关系表数据
              $data2['uid'] = $admin->id;
              $data2['role_id'] = $param['role_id'];
              
              model('AdminRoleAccess')->addData($data2); 
              return  success_json('添加成功');
          }else{
              return  error_json('添加失败');
          }

   }else{
      //显示所有角色
        $where[] =['role_id','neq',1];
        $list = model('adminRole')->listData($where);
        $this->assign('list',$list);
        return $this->fetch();
   }      
  }
  public function edit(){
    $param = $this->request->param(); 
    $uid = intval($param['id']); 
    if($this->request->isPost()){

       if($param['password']){
        //验证
        $rule =[
         'password'=>'require|min:6',
         'repassword'=>'require|min:6',
        ];
        $msg= [
         'password.require' =>'登陆密码不能为空',
         'password.min' =>'登陆密码至少6位',   
         'repassword.require' =>'重复密码不能为空',
         'repassword.min' =>'重复密码至少6位',  
          ];
         $error = $this->checkSubmit($param,$rule,$msg);  
         if($error){
              return error_json($error);
         }

        
             // 验证两次密码输入是否一致
             if($param['repassword'] != $param['password']){
                  return error_json('重复密码与登录密码不一致'); 
             }  

          $where['uid'] = $uid;
          $admin = model('Admin')->getAdminInfo($where);
          
          $data['password'] = password_key($admin['username'],$param['password'],$admin['passsalt']);
          
         }


 
         //表单数据
         
          $data['status'] = !empty($param['status'])?1:0;
          $where['uid'] = $uid;
          model('admin')->editData($data,$where);




       //角色用户关系表
          $where2['uid']    = $uid;
          if(!empty($param['role_id'])){
          $data2['role_id'] = $param['role_id'];
          //编辑关系表数据
          model('AdminRoleAccess')->editData($data2,$where2); 
           }
     
          return  success_json('编辑成功');
    }else{
         //获得管理员信息
          $where['uid'] = $uid;
          $admin = model('Admin')->getAdminInfo($where);

         $adminRoleAccess = model('adminRoleAccess')->where($where)->find();
          $admin['role_id'] = $adminRoleAccess['role_id'];
          $this->assign('admin',$admin);        
         //所有权限列表
         $where2[] =['role_id','neq',1];
         $list = model('AdminRole')->listData($where2);
         $this->assign('list',$list);
         //获得当前管理员的权限ID
      
         $res  = model('AdminRoleAccess')->getAdminRoleId($uid);
         $this->assign('role_id',$res['role_id']);
         return $this->fetch();


    }  
  }
  //批量删除或者单个删除
  public function del(){
       $param = $this->request->param();
       if(!$param['id']){  return error_json('请求参数错误');    }
         $id = $param['id'];  
         if(is_array($id)){
           $ids = implode(',',$id);
         }else{
           $ids = $id;
         }  
         $map[]= ['uid','in',$ids];
       //删除管理员
       
       if(model('admin')->delData($map)){
          $map2[] = ['uid','in',$ids];
         //删除关系表
         $res = model('AdminRoleAccess')->delData($map2);  
         if($res){
           return success_json('删除成功');
         }    
       }


      

  }
      

}